import Vue from 'vue'
import Vuex from 'vuex'
import persistedState from 'vuex-persistedstate'

Vue.use(Vuex)

const store = new Vuex.Store({
	plugins: [
		// 持久化用, 防止刷新丢失数据，通过 storage 存储
		persistedState({
			storage: {
				getItem: (key) => uni.getStorageSync(key),
				setItem: (key, value) => uni.setStorageSync(key, value),
				removeItem: (key) => uni.removeStorageSync(key),
			},
		}),
	],
	// 数据参数
	state: {
		userInfo: null,
	},
	// 计算属性
	getters: {
		isLogin: (state) => {
			return state.userInfo != null
		}
	},
	// 同步方法
	mutations: {
		initUserInfo(state, payload) {
			console.log('here we are')
			state.userInfo = payload.userInfo
		},
	},
	// 异步方法
	actions: {
		getUserInfoAction({
			commit
		}, payload) {
			// 调用异步方法，获取 userInfo
			Promise.resolve({
				userInfo: {
					name: 'test'
				}
			}).then((data) =>
				commit('initUserInfo', data)
			)
		},
	},
})

export default store
